package com.bxx.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


import com.bxx.dao.ModuleDao;
import com.bxx.dao.RoleModuleDao;
import com.bxx.dao.UserDao;
import com.bxx.dao.UserRoleDao;
import com.bxx.pojo.*;
import com.bxx.service.ModuleService;
import com.bxx.service.UserService;
import com.bxx.util.DateParse;
import com.bxx.util.PageUtil;
import com.bxx.util.R;
import com.bxx.vo.TreeNodeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

	//用户持久层对象
	@Autowired
	private UserDao userDao;

	//注入用户角色持久层
	@Autowired
	private UserRoleDao userRoleDao;

	//注入角色模块持久层
	@Autowired
	private RoleModuleDao roleModuleDao;

	//注入模块持久层
	@Autowired
	private ModuleDao moduleDao;

	//注入模块业务层
	@Autowired
	private ModuleService moduleService;
	
	@Override
	public R login(LoginDTO loginDTO) {
		//获取用户
		User user=userDao.login(loginDTO.getLoginName());
		if(user!=null) {
			//判断用户是否锁定(0:否，1:是）
			if(user.getIsLock() == 0) {
				//判断密码是否正确
				if(loginDTO.getPassword().equals(user.getUserPassword())) {
						
					//修改用户最后登录时间
					user.setLastLoginTime(DateParse.parseTimeStamp(new Date()));
					userDao.updateUser(user);

					//创建用户传输对象
					UserDTO userDTO = new UserDTO();
					userDTO.setUserId(user.getUserId())
							.setUserName(user.getUserName());
						
					return R.ok("登录成功！").put("data",userDTO);

				}else {
					//密码错误次数加1
					if(user.getPwdWrongCount()==null) {
						user.setPwdWrongCount(0);
					}
					user.setPwdWrongCount(user.getPwdWrongCount()+1);
					//判断错误次数是否大于3
					if(user.getPwdWrongCount()>=3) {
						//锁定用户
						user.setIsLock(1);
					}
					//保存修改
					userDao.updateUser(user);
					return R.error("密码错误");
				}
			}else {
				return R.error("用户已锁定");
			}
		}else {
			return R.error("该用户不存在！");
		}
	}

	@Override
	public PageUtil<User> listUsers(PageUtil<User> pageUtil) {
		List<User> users = userDao.listUsers(pageUtil);
		Integer usersCount = userDao.getUsersCount(pageUtil);
		pageUtil.setData(users);
		pageUtil.setCount(usersCount);
		return pageUtil;
	}



	@Override
	public R insertUser(User user) {
		user.setUserId(UUID.randomUUID().toString());
		user.setCreateTime(DateParse.parseTimeStamp(new Date()));
		user.setHeadImg("default.jpg");
		user.setIsLock(0);
		user.setPwdWrongCount(0);

		Integer r = userDao.insertUser(user);
		if(r>0){
			return R.ok("新增成功");
		}else {
			return R.error("新增失败");
		}
	}


	@Transactional //开启事务
	@Override
	public R updateUser(User user){
		System.out.println("updateUser.user>"+user);
		//获取用户的原数据
		User newUser = userDao.getUserById(user.getUserId());
		System.out.println("updateUser.newUser>"+user);
		newUser.setUserEmail(user.getUserEmail());
		newUser.setPhoneNumber(user.getPhoneNumber());
		newUser.setUpdateTime(DateParse.parseTimeStamp(new Date()));
		Integer r = userDao.updateUser(newUser);

		if(r>0){
			return R.ok("修改成功");
		}else {
			return R.error("修改失败");
		}

	}

	@Transactional //开启事务
	@Override
	public R deleteUser(String userId) {

		Integer r = userDao.deleteUser(userId);
		if(r>0){
			return R.ok("删除成功");
		}else {
			return R.error("删除失败");
		}
	}

	@Override
	public R rePassword(String userId) {
		String newPwd = "123456";
		User user = new User();
		user.setUserId(userId);
		user.setUserPassword(newPwd);
		user.setUpdateTime(DateParse.parseTimeStamp(new Date()));
		Integer r = userDao.updateUser(user);

		if(r>0){
			return R.ok("该用户密码已重置为：" + newPwd);
		}else {
			return R.error("密码重置失败");
		}
	}

	@Override
	public R lockOrUnlock(User user) {
		user.setUpdateTime(DateParse.parseTimeStamp(new Date()));
		Integer r = userDao.updateUser(user);
		R res = null;
		String str = "";
		if(user.getIsLock() == 0){
			str = "解锁";
		}else {
			str = "锁定";
		}
		if(r>0){
			return R.ok(str + "成功");
		}else {
			return R.error(str + "失败");
		}
	}

	@Override
	public List<TreeNodeVO> getFunctionMenu(String userId) {
		//获取用户拥有的角色
		List<UserRole> userRoles = userRoleDao.getUserRoleByUserId(userId);
		if (userRoles == null || userRoles.size() < 1){
			return null;
		}

		//根据角色id获取角色拥有的模块
		List<String> roleIdList = new ArrayList<String>();
		for (UserRole userRole : userRoles) {
			roleIdList.add(userRole.getRoleId());
		}

		//根据角色id获取角色拥有的模块信息
		List<Integer> moduleIdList = roleModuleDao.getModuleIdByRoleIdList(roleIdList);

		//根据模块id集合获取模块信息
		List<Module> modules = moduleDao.getModulesByModuleIdList(moduleIdList);

		//转换成树结构
		List<TreeNodeVO> treeNodeVOs = moduleService.convertModuleTree(modules);

		return treeNodeVOs;
	}

	@Override
	public List<User> ListUser(PageUtil<User> pageUtil) {
		return userDao.ListUser(pageUtil);
	}


}
